package com.hmdp.listeners;

import com.hmdp.entity.VoucherOrder;
import com.hmdp.service.IVoucherOrderService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class VoucherListener {
    @Resource
    private RedissonClient redissonClient;

    @Resource
    private IVoucherOrderService iVoucherOrderService;
    @RabbitListener(queues = "voucher.direct.queue")
    private void handlerVouchOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        //创建锁
        //SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //设置锁过期是为了防止任务执行时间过长，当任务执行之后，释放锁会删除这个锁，这个时候其他人来得到这个锁
        //就会又把锁的时间设置为5秒
        boolean islock = lock.tryLock();
        if (!islock) {
            return;
        }
        try {
            iVoucherOrderService.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }
}
